import './index.less';
import Utils from "../../../common/utils.js";
import DyDialog from '../../../components/h5/dyDialog';
// 主页
import galleryListView from "./index.html";
import headerPartial from "../index/partial/header.html";
import vListPartial from "../live/partial/videoList.html";
// 接口服务
import LiveService from "../../../services/liveService.js";
const liveService = new LiveService();

export default class GalleryList {
    constructor() {
        this.scrollIng = false;
        this.beginScroll = true;
        this.request = true;
        this.galleryContainer = $(".gallery-container");
        this.complied = _.template(galleryListView);
        this.compliedHeaderPartial = _.template(headerPartial);
        this.compliedVideoListPartial = _.template(vListPartial);
        this.token = Utils.GetToken();
        console.log("token是", this.token)
        this.id = Utils.GetQueryString('id');
        if (this.token == '') {
            alert("无法获取token")
        }
        this.render();
        this.dyURL = '';
        this.yqURL = ''
        this.WebSocketFn();
        this.start = 1;
        this.start2 = 1;
        this.length = 50;
        this.length2 = 30;
        this.isMore = true;
        this.isMore2 = true;
        this.lable = '';
        this.wjx = '';
        this.type = '',
            this.limitConnect = 3; // 断线重连次数
        this.timeConnect = 0;
        this.hasTop = false;
    }
    //渲染页面
    async render() {
        let _this = this;
        var liveList = {}
        var url = ''
        var pic = '';
        var bg_pic = '';
        //加载header
        let headerHtml = _this.compliedHeaderPartial({
            data: 2,
            token: _this.token
        });

        var type = '';
        var startTime = ''; //开始时间
        var item = {}

        if (_this.id == '') {
            console.log("没有ID")
            //获取新ID
            let result = await liveService.getLiveList(_this.token);
            console.log("result111", result)
            if (result.code == 200) {
                liveList = result.data;
            } else {
                alert('获取直播接口失败，请重试')
                return;
            }
            //有直播进行中显示直播
            for (var i of liveList) {
                if (i.status == "living") {
                    item = i;
                    type = "living"
                    break
                }
            }
            //有等待中的显示倒计时
            if (type != 'living') {
                for (var i of liveList) {
                    if (i.status == "waiting") {
                        item = i;
                        type = "waiting"
                        break
                    }
                }
                window.location = `/live.html?id=${item.id}&token=${_this.token}`
            }
            console.log(item, type)

            //没有直播显示回放
            if (type != 'living' && type != 'waiting') {
                for (var i of liveList) {
                    if (i.type == "play" && i.status == "end") {
                        item = i;
                        type = "end"
                        break
                    }
                }
                if (type == 'end') {
                    console.log("获取到点播视频", JSON.stringify(item))
                    window.location = `/video.html?id=${item.id}&token=${_this.token}`
                } else {
                    alert("无视频可播放")
                }
            }
            console.log("获取到直播视频", JSON.stringify(item))
            window.location = `/live.html?id=${item.id}&token=${_this.token}`

        } else {
            console.log("有ID")
            //获取新ID
            let result = await liveService.getLiveList(_this.token, _this.id);
            console.log("result", JSON.stringify(result))
            if (result.code == 200) {
                liveList = result.data;
                type = liveList.status;
                _this.type = liveList.status;
                pic = liveList.LiveDescImage;
                _this.lable = liveList.label;
                _this.wjx = liveList.questionnaire;
                startTime = liveList.StartTime
                $('title').html(liveList.title)
                console.log("MobilePlayImage", liveList.MobilePlayImage)
                bg_pic = liveList.MobilePlayImage
            } else {
                alert('获取直播接口失败，请重试')
                return;
            }
            console.log("type", type)
            //根据类型  做不同操作
            if (type == 'living' || type == 'waiting') {
                //显示直播
                let addressResult = await liveService.getLiveAddress(_this.token, _this.id);
                console.log("addressResult", addressResult)
                if (addressResult.code == 200) {
                    url = addressResult.data.pull.hls.main;

                } else {
                    alert('获取直播地址接口失败，请重试')
                    return;
                }
            } else if (type == "end") {
                //跳转点播
                window.location = `/video.html?id=${_this.id}&token=${_this.token}`
            } else {
                alert(`未知类型，type为${type}`)
                return;
            }
        }

        //相关视频 按label查询。
        let lable_result = await liveService.getLiveListByLabel(_this.token, '1', _this.lable, {
            start: 1,
            length: _this.length2
        });
        console.log("lable_result", lable_result)
        if (lable_result.code == 200) {
            lable_result_List = lable_result.data;
            if (lable_result_List.length >= _this.length2) {
                _this.start2 = _this.start2 + 1;
            } else {
                //已无更多数据，不再加载。
                _this.isMore2 = false;
            }
        } else {
            // alert('获取相关视频失败，请重试')
            return;
        }


        //获取聊天记录
        let chatMsgResult = await liveService.getChatMsg(_this.token, _this.id, _this.start, _this.length);
        console.log("chatMsgResult", chatMsgResult)
        if (chatMsgResult.code == 200) {
            chatMsg = chatMsgResult.data.reverse();
            if (chatMsg.length >= _this.length) {
                _this.start = _this.start + 1;
            }
        } else {
            console.log(chatMsgResult.message)
        }

        //获取TOP聊天记录
        let chatMsgTopResult = await liveService.getChatMsg2(_this.token, _this.id, 1, _this.length);
        console.log("chatMsgTopResult", chatMsgTopResult)
        if (chatMsgTopResult.code == 200) {
            var chatMsgList = chatMsgTopResult.data
            var chatTopMessage = chatMsgList[chatMsgList.length - 1]
            console.log(chatTopMessage, _this.hasTop)
            setTimeout(() => {
                if (!_this.hasTop && chatTopMessage.NickName) {
                    $("#gly").removeClass('gly_none')
                    $("#topMsg").html(`${chatTopMessage.NickName}：${chatTopMessage.message}`)
                }
            }, 20);
        } else {
            console.log(chatMsgTopResult.message)
        }


        //整个页面列表
        let galleryListHtml = this.complied({
            pic: pic,
            chatMsg: chatMsg
        });
        $(".content").html(galleryListHtml);
        let vlistHtml = _this.compliedVideoListPartial({
            lable_result_List: lable_result_List.splice(0, _this.length),
        });
        $(".videos").html(vlistHtml);


        setTimeout(() => {
            $(".header-container").html(headerHtml);
            $('.emoji_box').toggle();
        }, 100);
        this.registerEvents();


        if (type == 'waiting') {

            let time = ''
            //获取倒计时
            let time_result = await liveService.getTime(this.token);
            console.log("time_result", time_result)
            if (time_result.code == 200) {
                time = time_result.data.t;
            } else {
                alert("获取服务器时间失败，请重试")
                return;
            }


            var timer = ''
            //倒计时开始时间
            var date = new Date(time.replace(/-/g, "/"));
            var now = date.getTime();
            //倒计时结束时间
            var endDate = new Date(startTime.replace(/-/g, "/"));
            var end = endDate.getTime();
            //时间差
            var time1 = end - now;
            if (time1 > 0) {
                //显示倒计时  隐藏视频 
                $("#live_video").addClass('hide');
                $("#live_video_timer").css({
                    'background': `no-repeat url(${bg_pic})`,
                    'background-size': '100%'
                })
                $("#live_video_timer").removeClass('hide');
                $("#live_video_timer2").removeClass('hide');
                $("#live_video_timer3").removeClass('hide');
                timer = setInterval(() => {
                    countTime(time1 - 1000)
                }, 1000);
            } else {
                // 没有倒计时，改用直播。
                console.log("直播地址", url)
                _this.type = 'living'
                var player = new TcPlayer('live_video', {
                    'm3u8': url, //这是hls地址
                    "autoplay": false, //iOS 下 safari 浏览器，以及大部分移动端浏览器是不开放视频自动播放这个能力的
                    "poster": bg_pic,
                    'controls': 'system'
                });
            }


            function countTime(leftTime) {
                time1 = leftTime
                //定义变量 d,h,m,s保存倒计时的时间
                var d, h, m, s;
                if (leftTime >= 0) {
                    d = Math.floor(leftTime / 1000 / 60 / 60 / 24);
                    h = Math.floor(leftTime / 1000 / 60 / 60 % 24);
                    m = Math.floor(leftTime / 1000 / 60 % 60);
                    s = Math.floor(leftTime / 1000 % 60);
                } else {
                    //刷新
                    window.location.reload();
                }
                //将倒计时赋值到div中
                document.getElementById("_d").innerHTML = d || 0 + "";
                document.getElementById("_h").innerHTML = h || 0 + "";
                document.getElementById("_m").innerHTML = m || 0 + "";
                document.getElementById("_s").innerHTML = s || 0 + "";

            }
        } else {
            console.log("直播地址", url)
            var player = new TcPlayer('live_video', {
                'm3u8': url, //这是hls地址
                "autoplay": false, //iOS 下 safari 浏览器，以及大部分移动端浏览器是不开放视频自动播放这个能力的
                // "poster": bg_pic,
                'controls': 'system'
            });
        }


        console.log(_this.wjx)
        var script = document.createElement('script');

        script.type = 'text/javascript';
        script.id = 'wjxFloatBtnJsCode';
        script.src = _this.wjx;
        if (_this.wjx) {
            document.getElementsByTagName('head')[0].appendChild(script);
        }









    }

    // 判断是否支持 WebSocket
    WebSocketFn() {
        var _this = this;
        console.log("hah")
        if ("WebSocket" in window) {
            console.log("222")
            ws = $.websocket({
                domain: "api.hljpckj.com", //这是与服务器的域名或IP
                port: 8080, //这是服务器端口号
                protocol: `api/v1/chat/${_this.id}?token=` + _this.token, //这东西可有可无,组合起来就是 ws://www.qhnovel.com:8080/test
                onOpen: function(event) {
                    console.log("已经与服务端握手");
                    _this.limitConnect = 3; // 断线重连次数
                    _this.timeConnect = 0;
                },
                onError: function(event) {
                    console.log("发生了错误,onError可省略不写");
                },
                onSend: function(msg) {
                    console.log("发送数据额外的代码,可省略不写");
                },
                onclose: function(param) {
                    console.log('服务器已经断开');
                    _this.reconnect();
                },
                onMessage: function(result, nTime) {
                    let ws_json_data = JSON.parse(result);
                    console.log("从服务端收到的数据:" + result);
                    var str = '';
                    if (ws_json_data.MsgType == 'NewChat') {
                        if (ws_json_data.is_admin) {
                            str = '<p><span class="gray"><img src="//www.hljpckj.com/assets/images/guan.png" class="guan" />' + ws_json_data.NickName + '：</span><span class="guan_text">' + ws_json_data.message + '</span></p>'
                            _this.hasTop = true;
                            $("#gly").removeClass('gly_none')
                            $("#topMsg").html(`${ws_json_data.NickName}：${ws_json_data.message}`)
                        } else {
                            str = '<p><span class="gray">' + ws_json_data.NickName + '：</span>' + ws_json_data.message + '</p>'
                        }

                    } else if (ws_json_data.MsgType == 'incoming') {
                        str = '<p class="gray">' + ws_json_data.NickName + '进入直播间</p>'
                    }
                    $(".chatList").append(str);
                    //滚动到最下方
                    var ele = document.getElementById('chatList');
                    if (ele) {
                        ele.scrollTop = ele.scrollHeight;
                    }

                }
            });
            setInterval(function() {
                console.log("心跳")
                ws.send(
                    JSON.stringify({
                        "MsgType": 'heartbeat'
                    })
                );
            }, 1000 * 300)
        } else {
            alert("您的浏览器暂不支持聊天功能");
        }
    }

    // 重连
    reconnect() {
        var _this = this;
        // lockReconnect加锁，防止onclose、onerror两次重连
        if (_this.limitConnect > 0) {
            _this.limitConnect--;
            _this.timeConnect++;
            console.log("第" + _this.timeConnect + "次重连");
            // 进行重连
            console.log("1111", _this.limitConnect)
            if (_this.timeConnect == 1) {
                _this.WebSocketFn();
            } else {
                setTimeout(function() {
                    console.log("20")
                    _this.WebSocketFn();
                }, 20 * 1000);
            }
        } else {
            console.log("TCP连接已超时");
        }
    }


    //绑定事件
    registerEvents() {
        let _this = this;
        $('.chatList').scroll(async function() {
            if (_this.isMore == false) {
                return;
            }
            if ($('.chatList p:first').offset().top - $('.chatList').offset().top == 0) {
                console.log("聊天区滚动到顶部")
                //获取聊天记录
                let chatMsgResult = await liveService.getChatMsg(_this.token, _this.id, _this.start, _this.length);
                console.log("新chatMsgResult", chatMsgResult)
                if (chatMsgResult.code == 200) {
                    chatMsg = chatMsgResult.data.reverse();
                    if (chatMsg.length >= _this.length) {
                        _this.start = _this.start + 1;
                    } else {
                        //已无更多数据，不再加载。
                        _this.isMore = false;
                    }
                    var str = '';
                    for (var i = 0; i < chatMsg.length; i++) {
                        if (chatMsg[i].is_admin) {
                            str = str + '<p><span class="gray"><img src="//www.hljpckj.com/assets/images/guan.png" class="guan" />' + chatMsg[i].NickName + '；</span><span class="guan_text">' + chatMsg[i].message + '</span></p>'
                        } else {
                            str = str + '<p><span class="gray">' + chatMsg[i].NickName + '：</span>' + chatMsg[i].message + '</p>'
                        }

                    }
                    $(".chatList").prepend(str);
                } else {
                    console.log(chatMsgResult.message)
                }
            }
        })
        //切换菜单
        $('ul li').click(function() {
            $(this).addClass('active');
            $(this).siblings().removeClass('active');
            $('.tab_content .content_box').eq($(this).index()).addClass('div_show');
            $('.tab_content .content_box').eq($(this).index()).siblings().removeClass('div_show');
            if ($(this).index() == 1) {
                //限制聊天区域高度
                var chat_top = $('.chatList').offset().top;
                var body_height = $('.inputBox').offset().top;
                console.log(chat_top)
                $('.chatList').css({
                    height: `${(body_height-chat_top)}px`,
                    overflow: 'scroll'
                })
                //聊天区域滚动到最下方
                var ele = document.getElementById('chatList');
                ele.scrollTop = ele.scrollHeight;
            }
            console.log($(this).index())
            console.log($('.tab_content .content_box').eq($(this).index()))
        })

        //相关视频
        $('.video_container').delegate(".videoItem", "click", function() {
            var id = $(this).attr('data-id')
            if ($(this).attr('data-status') == 'end') {
                window.location = `/video.html?id=${id}&token=${_this.token}`
            } else {
                window.location = `/live.html?id=${id}&token=${_this.token}`
            }

        });

        //订阅
        $('.video_container').delegate(".dy2", "click", async function() {
            if (_this.dyURL == '') {
                let qr = await liveService.getQR(_this.token);
                console.log("qr", qr)
                if (qr.code == 200) {
                    _this.dyURL = 'data:image/png;base64,' + qr.data.url;
                    new DyDialog(_this.dyURL, _this.type);
                } else {
                    console.log("qr.message", qr.message)
                }
            } else {
                new DyDialog(_this.dyURL, _this.type);
            }
        });

        $('.video_container').delegate(".yq", "click", async function() {
            if (_this.yqURL == '') {
                let yq = await liveService.getQR2(_this.token, _this.id);
                console.log("yq", yq)
                if (yq.code == 200) {
                    _this.yqURL = 'data:image/png;base64,' + yq.data.url;
                    new DyDialog(_this.yqURL, _this.type);
                } else {
                    console.log("yq.message", yq.message)
                }
            } else {
                new DyDialog(_this.yqURL, _this.type);
            }
        });

        // Input 回车
        $('#input_bottom').keyup(function(event) {
            var event = event || window.event;
            if (event.keyCode === 13) {
                var send_i_v = $("#input_bottom").val();
                $("#input_bottom").val(" ");
                console.log(send_i_v)
                onSendWSFn(send_i_v);
            }
        });
        // 发送聊天消息
        $("#send").click(function() {
            var send_i_v = $("#input_bottom").val();
            $("#input_bottom").val(" ");
            console.log(send_i_v)
            onSendWSFn(send_i_v);
        });
        //显示隐藏表情区
        $('.inputBox').delegate('.emojiBtn', 'click', function(e) {
            console.log("显示隐藏表情区")
            $('.emoji_box').toggle();
        })
        //点击表情 发送表情
        $('.emoji_box').delegate('span', 'click', function(e) {
            console.log("发送表情", e.target.innerText)
            var send_i_v = e.target.innerText;
            onSendWSFn(send_i_v);
            $('.emoji_box').hide(); //关闭表情区
        })

        // ws 发送 通讯 
        function onSendWSFn(send_i_v) {
            console.log("id", _this.id)
            if (send_i_v.trim()) {
                ws.send(
                    JSON.stringify({
                        "RoomId": _this.id,
                        "message": send_i_v
                    })
                );
            }
        }

        function debounce(fn, wait) {
            var timeout = null;
            return function() {
                if (timeout !== null) clearTimeout(timeout);
                timeout = setTimeout(fn, wait);
            }
        }

        async function handle() {
            console.log("jiazai11")
            var scrollTop = $(this).scrollTop();
            var scrollHeight = $(document).height();
            var windowHeight = $(this).height();
            if (scrollTop + windowHeight + 5 >= scrollHeight) {

                console.log("jiazai")
                if (_this.isMore2 == false) {
                    console.log("无需加载了")
                    return;
                }
                //相关视频 按label查询。
                let lable_result = await liveService.getLiveListByLabel(_this.token, '1', _this.lable, {
                    start: _this.start2,
                    length: _this.length2
                });
                console.log("继续加载resultlable_result", lable_result)
                if (lable_result.code == 200) {
                    lable_result_List = lable_result.data;

                    if (lable_result_List.length >= _this.length2) {
                        _this.start2 = _this.start2 + 1;
                    } else {
                        //已无更多数据，不再加载。
                        _this.isMore2 = false;
                    }
                } else {
                    // alert('获取相关视频失败，请重试')
                    return;
                }

                let vlistHtml = _this.compliedVideoListPartial({
                    lable_result_List: lable_result_List,
                });
                $(".videos").append(vlistHtml);
            }
        }
        //滚动加载
        window.addEventListener('scroll', debounce(handle, 300));

    }
}